<template>
  <Card class="w-full" :title="title">
    <template #extra>
      <Button
        class="m-2"
        type="primary"
        v-for="item in tableButtons"
        @click="handleTableClick(item)"
        >{{ item.name }}
      </Button>
    </template>
    <BasicForm @register="registerForm" @submit="handleSubmit" />
    <Button
      class="m-2"
      type="primary"
      v-for="item in columnButtons"
      @click="handleColumnClick({ props: {...wholeValue}, option: item })"
      >{{ item.name }}
    </Button>
  </Card>
</template>
<script lang="ts" setup>
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Button, Card } from 'ant-design-vue';
  import { BasicForm, FormSchema, useForm } from '@/components/Form';
  import { unref } from 'vue';

  const emit = defineEmits(['success', 'register']);

  const props = defineProps({
    handleColumnClick: {
      type: Function,
    },
    columnButtons: {
      type: Array,
    },
    title: {
      type: String,
    },
    rowKey: {
      type: [String, Number],
    },
    handleSuccess: {
      type: Function,
    },
    api: {
      type: Function,
    },
    tableButtons: {
      type: Array,
    },
    handleTableClick: {
      type: Function,
    },
    addSchemas: {
      type: Array<FormSchema>,
    },
    editSchemas: {
      type: Array<FormSchema>,
    },
  });

  // 默认新增表单
  const schemas = ref(props.addSchemas);
  const wholeValue = ref();
  const idValue = ref('');
  const isUpdate = ref(false);

  function initData() {
    props.api().then((res) => {
      let dataList = res.list;
      let dataItem = dataList[0];
      idValue.value = dataItem[props.rowKey];
      if (dataList) {
        isUpdate.value = true;
        wholeValue.value = dataItem;
        schemas.value = props.editSchemas;
        setFieldsValue(dataItem);
      }
    });
  }

  onMounted(() => {
    initData();
  });
  const { createMessage } = useMessage();
  const pkSchema = {};
  pkSchema[props.rowKey] = undefined;
  const [registerForm, { setProps, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: schemas,
    rowProps: { gutter: 16, justify: 'start' },
    labelAlign: 'left',
    showActionButtonGroup: false,
    showResetButton: false,
    showSubmitButton: true,
    submitButtonOptions: {
      text: '保存',
    },
    actionColOptions: {
      span: 23,
    },
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      values[props.rowKey] = idValue.value;
      emit('success', {
        isUpdate: unref(isUpdate),
        values: values,
        closeModal: () => {},
      });
    } finally {
      setTimeout(() => {
        initData();
      }, 200);
    }
  }
</script>
